<template>
  <div class="app-container">
    <!-- 条件搜索 -->
    <div class="filter-container">
      <el-form ref="queryForm" :model="listQuery.param" size="small" :inline="true" label-width="auto">
        <el-form-item label="所属应用" prop="serviceName">
          <el-input v-model="listQuery.param.serviceName" placeholder="所属应用" class="filter-item" @keyup.enter.native="handleFilterQuery" />
          <!--        <el-col :span="3">-->
          <!--          <el-select v-model="listQuery.param.serviceName" placeholder="所属应用" style="width: 100%" class="filter-item">-->
          <!--            <el-option v-for="item in serviceNameOptions" :key="item.code" :label="item.text" :value="item.code" />-->
          <!--          </el-select>-->
          <!--        </el-col>-->
        </el-form-item>
        <el-form-item label="使用状态" prop="status">
          <el-select v-model="listQuery.param.status" placeholder="使用状态" style="width: 150px;" class="filter-item" @change="handleFilterQuery">
            <el-option v-for="item in statusOptions" :key="item.code" :label="item.text" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" style="margin-left: 10px;" @click="handleFilterQuery">
          搜索
        </el-button>
        <el-button v-waves class="filter-item" icon="el-icon-refresh-right" @click="handleRestQuery">
          重置
        </el-button>
      </el-form>
      <el-row />
    </div>
    <div class="filter-container">
      <div style="float: left;">
        <el-button v-permission="permission.add" class="filter-item" type="primary" plain icon="el-icon-plus" @click="handleCreate">
          新增
        </el-button>
        <el-button v-permission="permission.gen" class="filter-item" type="primary" plain icon="el-icon-reading" @click="handleCoding">
          生成代码
        </el-button>
      </div>
      <div style="float: right;">
        <el-button icon="el-icon-refresh" circle @click="handleFilterQuery" />
      </div>
    </div>

    <!-- 数据表格 -->
    <el-table
      :key="tableKey"
      ref="dataTable"
      v-loading="loading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      scrollbar-always-on="true"
    >
      <el-table-column type="selection" width="50px" align="center" />
      <el-table-column label="序号" type="index" width="50px" align="center" />
      <el-table-column label="服务名称" min-width="100px" align="left">
        <template v-slot="{row}">
          <span>{{ row.serviceName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="数据库类型" min-width="80px" align="left">
        <template v-slot="{row}">
          <span>{{ row.type }}</span>
        </template>
      </el-table-column>
      <el-table-column label="数据库名" min-width="90px" align="left">
        <template v-slot="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="主机" min-width="100px" align="left">
        <template v-slot="{row}">
          <span>{{ row.host }}</span>
        </template>
      </el-table-column>
      <el-table-column label="端口" min-width="50px" align="left">
        <template v-slot="{row}">
          <span>{{ row.port }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户名" min-width="80px" align="left">
        <template v-slot="{row}">
          <span>{{ row.username }}</span>
        </template>
      </el-table-column>
      <el-table-column label="使用状态" class-name="status-col" width="70px">
        <template v-slot="{row}">
          <el-switch :value="row.status ==='Y'" disabled />
        </template>
      </el-table-column>
      <el-table-column label="备注" min-width="100px" align="left">
        <template v-slot="{row}">
          <span>{{ row.remark }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新人" min-width="70px" align="left">
        <template v-slot="{row}">
          <span>{{ row.updatedBy }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" width="160px" align="left">
        <template v-slot="{row}">
          <span>{{ row.updatedTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="160px" class-name="small-padding fixed-width">
        <template v-slot="{row,$index}">
          <el-button v-permission="permission.edit" size="mini" type="warning" icon="el-icon-edit" @click="handleUpdate(row)">编辑</el-button>
          <el-button v-permission="permission.del" size="mini" type="danger" icon="el-icon-delete" @click="handleDelete(row,$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 表格分页 -->
    <pagination :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize" @pagination="handleInit" />

    <!-- 编辑页面 -->
    <el-dialog :title="title[state]" :visible.sync="visible" :close-on-click-modal="false" width="800px" @close="handleClose">
      <el-form ref="dataForm" :rules="rules" :model="formData" label-position="right" label-width="100px">
        <el-input v-model="formData.id" type="hidden" />
        <el-row>
          <el-col :span="24">
            <el-form-item label="所属应用" prop="serviceName">
              <el-input v-model="formData.serviceName" placeholder="请输入" />
              <!--              <el-select v-model="formData.serviceName" placeholder="所属应用" style="width: 100%" class="filter-item">-->
              <!--                <el-option v-for="item in serviceNameOptions" :key="item.code" :label="item.text" :value="item.code" />-->
              <!--              </el-select>-->
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="数据库类型" prop="type">
              <el-select v-model="formData.type" placeholder="数据库类型" style="width: 100%" class="filter-item">
                <el-option v-for="item in dbTypeOptions" :key="item.code" :label="item.text" :value="item.code" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数据库名称" prop="name">
              <el-input v-model="formData.name" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="主机" prop="host">
              <el-input v-model="formData.host" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="端口" prop="port">
              <el-input v-model="formData.port" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="用户" prop="username">
              <el-input v-model="formData.username" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <el-input v-model="formData.password" type="password" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="使用状态" prop="status">
              <el-radio v-model="formData.status" label="Y">启用</el-radio>
              <el-radio v-model="formData.status" label="N">禁用</el-radio>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="formData.remark" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button icon="el-icon-close" @click="handleClose">
          取消
        </el-button>
        <el-button v-if="state !=='detail'" :loading="submitting" type="primary" icon="el-icon-check" @click="handleSubmitFormData">
          <span v-if="!submitting">确认</span>
          <span v-else>提 交 中...</span>
        </el-button>
      </div>
    </el-dialog>

    <!-- 数据表格（表信息列表） 组件 -->
    <code-form ref="codeForm" :code-form-params="codeForm" />

    <!--展示生成的代码-->
    <code-view ref="codeView" :code-view-params="codeView" />
  </div>
</template>

<script>
import { handleDict } from '@/api/ft'
import { getPageList, handleSave, handleDelete } from './api'
import waves from '@/directive/waves'
import permission from '@/directive/permission/index' // 权限判断指令
import Pagination from '@/components/Pagination'
import CodeForm from './code-form.vue'
import CodeView from './code-view.vue'

export default {
  // 当前页面名称（组件）
  name: 'CodeEditor',
  // 引用组件
  components: {
    Pagination,
    CodeForm,
    CodeView
  },
  directives: { permission, waves },
  filters: {},
  data() {
    return {
      // 列表table的key
      tableKey: 0,
      // 遮罩层
      loading: true,
      // table数据对象
      list: [],
      // 总条数
      total: 0,
      // table 条件查询对象
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        param: {
          serviceName: undefined,
          status: undefined
        }
      },
      statusOptions: [{ code: 'Y', text: '启用' }, { code: 'N', text: '禁用' }],
      serviceNameOptions: [],
      dbTypeOptions: [{ code: 'MySql', text: 'MySql' }, { code: 'Oracle', text: 'Oracle' }, { code: 'PostgreSQL', text: 'PostgreSQL' }],
      // 表单数据对象
      formData: {},
      // 是否显示弹出层
      visible: false,
      // 弹出层状态
      state: '',
      // 弹出层标题
      title: {
        update: '修改',
        create: '新增'
      },
      // 权限标识
      permission: {
        gen: ['tools:code:gen'],
        add: ['tools:code:add'],
        edit: ['tools:code:edit'],
        del: ['tools:code:del']
      },
      submitting: false,
      // 表单校验规则
      rules: {
        serviceName: [{ required: true, message: '所属服务不能为空', trigger: 'blur' }],
        type: [{ required: true, message: '数据库类型不能为空', trigger: 'blur' }],
        name: [{ required: true, message: '数据库名称不能为空', trigger: 'blur' }],
        host: [{ required: true, message: '主机地址不能为空', trigger: 'blur' }],
        port: [{ required: true, message: '端口号不能为空', trigger: 'blur' }],
        username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
        password: [{ required: true, message: '密码不能为空', trigger: 'blur' }]
      },
      // 子组件数据对象
      codeForm: {
        visible: false,
        formData: {
          serviceName: undefined,
          type: undefined,
          name: undefined,
          host: undefined,
          port: undefined,
          username: undefined,
          password: undefined,
          tableName: undefined,
          author: undefined,
          parent: undefined,
          moduleName: undefined,
          codeStyle: undefined,
          prefix: undefined
        }
      },
      codeView: {
        visible: false,
        tabData: []
      }
    }
  },
  computed: {},
  watch: {},
  created() {
    this.handleInit()
    this.handleRestFormData()
  },
  mounted() {},
  methods: {
    // 查询table数据对象
    handleInit() {
      this.loading = true
      getPageList(this.listQuery).then(res => {
        this.list = res.data
        if (res.total) {
          this.total = Number(res.total)
        }
        this.loading = false
      })
      handleDict({ type: 'service_name' }).then(res => {
        this.serviceNameOptions = Object.entries(res.data).map(([code, text]) => ({ code, text }))
      })
    },
    // 条件查询table数据
    handleFilterQuery() {
      this.listQuery.pageNum = 1
      this.handleInit()
    },
    // 重置table查询条件
    handleRestQuery() {
      this.$refs.queryForm.resetFields()
    },
    // 重置表单
    handleRestFormData() {
      this.formData = {
        id: undefined,
        serviceName: undefined,
        type: undefined,
        name: undefined,
        host: undefined,
        port: undefined,
        username: undefined,
        password: undefined,
        status: 'Y',
        remark: ''
      }
    },
    // 新增
    handleCreate() {
      this.state = 'create'
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 修改
    handleUpdate(row) {
      this.state = 'update'
      this.visible = true

      // 创建一个新的对象赋值
      this.formData = Object.assign({}, row)
      // 清理掉多余的属性值，避免数据不对问题
      delete this.formData.createdBy
      delete this.formData.createdTime
      delete this.formData.updatedBy
      delete this.formData.updatedTime
      delete this.formData.tenantId
      delete this.formData.revision
      delete this.formData.deleted

      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 删除
    handleDelete(row, index) {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 显示加载遮罩
        const loading = this.$loading({ lock: true, text: '处理中...', body: true, fullscreen: false, background: 'rgba(0, 0, 0, 0.05)' })
        handleDelete({ userId: row.userId }).then((res) => {
          loading.close()
          //  刷新table
          this.handleFilterQuery()
          this.$message({
            showClose: true,
            message: res.msg,
            type: 'success',
            duration: 4000
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 表单提交
    handleSubmitFormData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.submitting = true
          handleSave(this.formData).then((res) => {
            this.submitting = false
            //  刷新table
            this.handleFilterQuery()
            this.visible = false
            this.$message({
              showClose: true,
              message: res.msg,
              type: 'success',
              duration: 4000
            })
          })
        }
      })
    },
    // 代码生成
    handleCoding() {
      const selection = this.$refs.dataTable.selection
      if (selection.length !== 1) {
        this.$message({
          showClose: true,
          type: 'warning',
          message: '请选择一行记录操作！',
          duration: 4000
        })
        return
      }
      this.codeForm.formData = selection[0]
      this.codeForm.formData.author = this.$store.state.user.username
      this.codeForm.visible = true
      // 由于子组件是异步的，所以需要调用nextTick
      this.$nextTick(() => {
        // 调用子组件的方法
        this.$refs['codeForm'].init(selection[0].id)
      })
    },
    // 展示代码
    handleCodeView(param) {
      this.codeView.visible = param.visible
      this.codeView.tabData = param.tabData
      // 由于子组件是异步的，所以需要调用nextTick
      this.$nextTick(() => {
        // 调用子组件的方法
        this.$refs['codeView'].init()
      })
    },
    // 关闭弹出层
    handleClose() {
      this.handleRestFormData()
      this.visible = false
    }
  }
}
</script>
